﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Backend.JYD.Common
{
    public class StringHelper
    {
        /// <summary>
        /// 按位截取字符串长度，汉字两字节，其他一个字节。
        /// </summary>
        /// <returns></returns>
        public static string Truncate(string strVal, int len)
        {
            return StringHelper.Truncate(strVal, len, string.Empty); ;
        }

        /// <summary>
        /// 按位截取字符串长度，汉字两字节，其他一个字节。
        /// 截取后，内容变短，增加后缀。如：省略号（...），可以传空
        /// </summary>
        /// <returns></returns>
        public static string Truncate(string strVal, int len, string postfix)
        {
            if (string.IsNullOrEmpty(strVal)) return string.Empty;
            string temp = strVal;
            int strlen = System.Text.Encoding.Default.GetByteCount(strVal);
            if (strlen <= len)
            {
                return temp;
            }

            int tempLen = strVal.Length < strlen ? strVal.Length : strlen;
            for (int i = tempLen; i >= 0; i--)
            {
                temp = strVal.Substring(0, i);
                if (System.Text.Encoding.Default.GetByteCount(temp) <= len)
                {
                    return temp + postfix;
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 将列表转化为以分隔符delimeter分隔的字符串
        /// </summary>
        /// <param name="list">列表</param>
        /// <param name="delimeter">分隔符</param>
        /// <returns></returns>
        public static string List2String<T>(List<T> list, string delimeter)
        {
            string val = string.Empty;
            for (int i = 0; i < list.Count;i++ )
            {
                if (i > 0) val += delimeter;
                if (list[i] == null || string.IsNullOrEmpty(list[i].ToString())) continue;
                val += list[i].ToString();
            }
            return val;
        }
        public static List<T> String2List<T>(string strVal)
        {
            return String2List<T>(strVal, ',');
        }
        public static List<T> String2List<T>(string strVal, char delimeter)
        {
            var vals = strVal.Split(delimeter);
            List<T> list = new List<T>();
            foreach (var val in vals)
            {
                if (string.IsNullOrWhiteSpace(val)) continue;

                try
                {
                    T temp = (T)Convert.ChangeType(val, typeof(T));
                    list.Add(temp);
                }
                catch (Exception ex)
                {
                    LogHelper.Log(ex);
                }
            }
            return list;
        }

        /// <summary>
        /// 是否手机号码
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsMobilePhone(string value)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(value, @"^1[3,5,8]\d{9}$");
        }

        /// <summary>
        /// 确保该用户的输入没有恶意和截取字符串长度
        /// </summary>
        /// <param name="text">User's Input</param>
        /// <param name="maxLength">Maximum length of input</param>
        /// <returns>The cleaned up version of the input</returns>
        public static string CheckText(string text, int maxLength)
        {
            text = StringHelper.CheckText(text);
            if (text.Length > maxLength)
                text = text.Substring(0, maxLength);

            return text;
        }
        public static string CheckText(string text)
        {
            text = text.Trim();
            if (string.IsNullOrEmpty(text))
                return string.Empty;

            //删除脚本
            text = Regex.Replace(text, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);

            //删除HTML
            text = Regex.Replace(text, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"-->", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"<!--.*", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "xp_cmdshell", "", RegexOptions.IgnoreCase);

            //删除与数据库相关的词
            text = Regex.Replace(text, "select", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "insert", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "delete from", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "count''", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "drop table", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "truncate", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "asc", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "mid", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "char", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "xp_cmdshell", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "exec master", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "net localgroup administrators", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "and", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "net user", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "or", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "net", "", RegexOptions.IgnoreCase);
            //text = Regex.Replace(text, "-", "", RegexOptions.IgnoreCase);//固定电话的运行输入
            text = Regex.Replace(text, "delete", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "drop", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "script", "", RegexOptions.IgnoreCase);

            //特殊的字符
            text = text.Replace("<", "");
            text = text.Replace(">", "");
            text = text.Replace("*", "");
            //text = text.Replace("-", "");//固定电话的运行输入
            text = text.Replace("?", "");
           //注释掉了 这个方式不对
            // text = text.Replace("'", "''");
            text = text.Replace(",", "");
            text = text.Replace("/", "");
            text = text.Replace(";", "");
            text = text.Replace("*/", "");
            text = text.Replace("\r\n", "");
            text = text.Replace("\r","");
            text = text.Replace("\n","");
            //text = HttpContext.Current.Server.HtmlEncode(text).Trim();

            //text = Regex.Replace(text, "[\\s]{2,}", " ");	//two or more spaces
            //text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");	//<br>
            //text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");	//&nbsp;
            //text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty);	//any other tags
            //text = text.Replace("'", "''");

            return text;
        }

    }
}
